package com.handinfo.android.core.net;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.view.Display;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.resource.ResourceVerifier;
import com.handinfo.android.uicontrols.DWControlsManager;
import com.handinfo.android.uicontrols.DWListener;
import com.handinfo.android.uicontrols.controls.DWMessageBox;
import com.handinfo.android.utils.Tools;


/**
 * HTTPConnect
 * @author 赵铮
 * */
public class HttpConnect implements Runnable
{
	public String SERVER;
	public String HOST;
	private String[] m_url;
	public int m_index;
	public String m_title = "提示";
	public String m_right = "退出";
	public String[] m_info = {"游戏将于11月12号10点30分盛世公测!",
			                  "服务器更新中，暂时无法连接!",
			                  "游戏维护中，全新资料片即将开启!"};
	
	/**
	 * @param SERVER
	 * @Param HOST
	 * */
	public HttpConnect(String server, String host)
	{
		SERVER = server;
		HOST = host;
		m_url = null;
	}
	
	public void connect() throws ClientProtocolException, IOException{
		String httpUrl = "http://"+HOST +"/"+ SERVER;
		httpUrl = httpUrl.trim();
		m_url = null;
		//HttpPost连接对象        
		HttpPost httpRequest = new HttpPost(httpUrl);
		//设置http参数
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, 5000);
		HttpConnectionParams.setSoTimeout(params, 6000);
		//取得默认的HttpClient
		HttpClient httpclient = new DefaultHttpClient(params);
		//取得HttpResponse          
		HttpResponse httpResponse = httpclient.execute(httpRequest);
		//HttpStatus.SC_OK表示连接成功           
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		{ 
			//取得返回的字符串                
			String strResult = EntityUtils.toString(httpResponse.getEntity());
			Tools.debugPrintln("strResult="+strResult);
			m_url = Tools.splitString(strResult, ',');
			if(m_url == null 
					|| m_url.length != 3 ){
					success(null, null);
				}else{
				    m_index = Integer.parseInt(m_url[0].trim());
				    Tools.debugPrintln("HTTP index="+m_index);
			        if (m_index == 10000){//成功			    	
				    	success(m_url[1], m_url[2]);
				    }else if(m_index < 0 || m_index > m_info.length - 1){//参数错误
				    	success(null, null);
				    }
			        else{//失败
			        	failure(m_index);
				    }
				}
		}else{
			success(null, null);
			Tools.debugPrintln("HTTP 状态失败");
		}
		httpRequest = null;
		httpclient = null;
		httpResponse = null;
	}
	
	
	public void failure(int index){
		final DWMessageBox box = new DWMessageBox(m_title, m_info[index],null,m_right);
		DWControlsManager.getInstance().addControl(box);
		box.addListener(new DWListener() {
			
			public void OnDoubleClick()
			{
				// TODO Auto-generated method stub
				
			}
			
			public void OnClick()
			{
				byte state = box.getResult();
				if(state == DWMessageBox.SOFTKEY_BACK){
					DWGameManager.getInstance().getGameHandler().setRunning(false);
					DWGameManager.getInstance().setRunning(false);
				}	
			}
		});
	}
	
	public void success(String param1,String param2){
    	setServerPost(param1, param2);
    	Object obj = DWGameManager.getInstance().getGameHandler();
    	if(obj != null && obj instanceof ResourceVerifier){    		
    		ResourceVerifier vr = (ResourceVerifier)obj;
    			vr.setState(ResourceVerifier.LOGIC_Waite_Connection);
    	}else{
    		Tools.debugPrintln("success Handler 对象不合法");
    	}
	}
	
	public void setServerPost(String server,String post){
		// 夏明炜改于2012.12.5
		if (server == null
				|| server.length() < 1
				|| post == null
				|| post.length() < 1) {
//			if(!Tools.DEBUG){			
//				DWGameManager.SERVER_URL = "211.151.33.71";
//				DWGameManager.SERVER_PORT = 23594;
//			}
		}
		else {
			if (!Tools.DEBUG) {
				DWGameManager.getInstance().setConnectionServiceInfo(server, Integer.parseInt(post.trim()));
			}
		}
		Tools.debugPrintln("SERVER_URL="+DWGameManager.SERVER_URL+"; SERVER_PORT="+DWGameManager.SERVER_PORT);
	}

	public void run()
	{
		try {
			Tools.debugPrintln("准备HTTP请求服务器列表信息");
			connect();
		}
		catch (ClientProtocolException e) {
			Tools.debugPrintln("ClientProtocolException");
			success(null, null);
			Tools.debug(e);
		}
		catch (IOException e) {
			Tools.debugPrintln("IOException");
			success(null, null);
			Tools.debug(e);
		}	
	}

}
